package com.umgsai.thread.thread53;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyService {
	private ReentrantLock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	public void waitMethod() {
		try {
			lock.lock();
			condition.await();//进入WAITTING状态，释放锁
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	public void notifyMethod() {
		try {
			lock.lock();
			System.out.println("是否有线程正在等待condition:" + lock.hasWaiters(condition));
			System.out.println("正在等待condition的线程数是：" + lock.getWaitQueueLength(condition));//10个线程等待
			condition.signal();//唤醒一个线程
			System.out.println("正在等待condition的线程数是：" + lock.getWaitQueueLength(condition));//9个线程等待
			condition.signalAll();//剩下的个全部唤醒
			System.out.println("正在等待condition的线程数是：" + lock.getWaitQueueLength(condition));//0个线程等待
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
	}
	public static void main(String[] args) throws InterruptedException {
		final MyService service = new MyService();
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				service.waitMethod();
			}
		};
		Thread[] threads = new Thread[10];
		for (int i = 0; i < threads.length; i++) {
			threads[i] = new Thread(runnable);
			threads[i].start();
		}
		Thread.sleep(2000);
		service.notifyMethod();
	}
}
